"""
课程管理路由 - CRUD操作
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.blueprints.api import api_bp
from app.models.user import User
from app.models.course import Course, CourseTag, CoursePrerequisite
from app.models.log import SystemLog
from app.extensions import db
from datetime import datetime


@api_bp.route('/courses', methods=['POST'])
@jwt_required()
def create_course():
    """创建课程"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        # 只有管理员可以创建课程
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['code', 'name', 'credits']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'success': False,
                    'error': f'Missing required field: {field}'
                }), 400
        
        # 检查课程代码是否已存在
        if Course.query.filter_by(code=data['code']).first():
            return jsonify({
                'success': False,
                'error': 'Course code already exists'
            }), 400
        
        # 查找教师
        instructor_id = None
        if 'instructor_id' in data:
            instructor = User.query.filter_by(id=data['instructor_id'], role='teacher').first()
            if instructor:
                instructor_id = instructor.id
        
        # 创建课程
        course = Course(
            code=data['code'],
            name=data['name'],
            description=data.get('description', ''),
            credits=float(data['credits']),
            department=data.get('department', ''),
            instructor_id=instructor_id,
            semester=data.get('semester', ''),
            max_students=data.get('max_students')
        )
        
        db.session.add(course)
        db.session.flush()
        
        # 添加标签
        if 'tags' in data and data['tags']:
            tags = data['tags'] if isinstance(data['tags'], list) else data['tags'].split(',')
            for tag_name in tags:
                tag_name = tag_name.strip()
                if tag_name:
                    tag = CourseTag(course_id=course.id, tag=tag_name)
                    db.session.add(tag)
        
        # 从 schedule 文本提取时间标签（用于冲突检测）
        schedule_text = data.get('schedule') or ''
        if schedule_text:
            import re
            cn_map = {'一':1,'二':2,'三':3,'四':4,'五':5,'六':6,'日':7,'天':7}
            m = re.search(r'周([一二三四五六日天])\s*(\d+)(?:\s*-\s*(\d+))?', schedule_text)
            if m:
                dow = cn_map.get(m.group(1))
                start = int(m.group(2))
                end = int(m.group(3) or start)
                db.session.add(CourseTag(course_id=course.id, tag=f'dow-{dow}'))
                db.session.add(CourseTag(course_id=course.id, tag=f'slot-{start}-{end}'))
        
        # 添加先修课程
        if 'prerequisites' in data and data['prerequisites']:
            for prereq_id in data['prerequisites']:
                prereq = CoursePrerequisite(
                    course_id=course.id,
                    prerequisite_id=prereq_id
                )
                db.session.add(prereq)
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='create',
            resource_type='course',
            resource_id=str(course.id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Created course {course.code}'
        )
        db.session.add(log)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Course created successfully',
            'data': course.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/courses/<int:course_id>', methods=['PUT'])
@jwt_required()
def update_course(course_id):
    """更新课程信息"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        course = Course.query.get(course_id)
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found'
            }), 404
        
        data = request.get_json()
        
        # 更新课程信息
        if 'name' in data:
            course.name = data['name']
        if 'description' in data:
            course.description = data['description']
        if 'credits' in data:
            course.credits = float(data['credits'])
        if 'department' in data:
            course.department = data['department']
        if 'semester' in data:
            course.semester = data['semester']
        if 'academic_year' in data:
            course.academic_year = data['academic_year']
        if 'semester_term' in data:
            course.semester_term = data['semester_term']
        if 'max_students' in data:
            course.max_students = data['max_students']
        if 'instructor_id' in data:
            course.instructor_id = data['instructor_id']
        
        # 如果更新了 schedule，重建时间标签
        if 'schedule' in data:
            # 删除旧时间标签
            CourseTag.query.filter(
                CourseTag.course_id == course.id,
                db.or_(CourseTag.tag.like('dow-%'), CourseTag.tag.like('slot-%'))
            ).delete(synchronize_session=False)
            schedule_text = data.get('schedule') or ''
            if schedule_text:
                import re
                cn_map = {'一':1,'二':2,'三':3,'四':4,'五':5,'六':6,'日':7,'天':7}
                m = re.search(r'周([一二三四五六日天])\s*(\d+)(?:\s*-\s*(\d+))?', schedule_text)
                if m:
                    dow = cn_map.get(m.group(1))
                    start = int(m.group(2))
                    end = int(m.group(3) or start)
                    db.session.add(CourseTag(course_id=course.id, tag=f'dow-{dow}'))
                    db.session.add(CourseTag(course_id=course.id, tag=f'slot-{start}-{end}'))
        
        # 更新标签
        if 'tags' in data:
            # 删除旧标签
            CourseTag.query.filter_by(course_id=course.id).delete()
            # 添加新标签
            tags = data['tags'] if isinstance(data['tags'], list) else data['tags'].split(',')
            for tag_name in tags:
                tag_name = tag_name.strip()
                if tag_name:
                    tag = CourseTag(course_id=course.id, tag=tag_name)
                    db.session.add(tag)
        
        course.updated_at = datetime.utcnow()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='update',
            resource_type='course',
            resource_id=str(course_id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'Updated course {course.code}'
        )
        db.session.add(log)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Course updated successfully',
            'data': course.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/courses/<int:course_id>', methods=['DELETE'])
@jwt_required()
def delete_course(course_id):
    """删除课程"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        course = Course.query.get(course_id)
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found'
            }), 404
        
        course_code = course.code
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='delete',
            resource_type='course',
            resource_id=str(course_id),
            ip_address=request.remote_addr,
            status='success',
            level='WARNING',
            message=f'Deleted course {course_code}'
        )
        db.session.add(log)
        
        # 删除课程（级联删除相关数据）
        db.session.delete(course)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Course deleted successfully'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/courses/<int:course_id>/students', methods=['GET'])
@jwt_required()
def get_course_students(course_id):
    """获取课程的学生列表"""
    try:
        course = Course.query.get(course_id)
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found'
            }), 404
        
        students = []
        for sc in course.student_courses:
            # 跳过无效记录
            if not sc.student:
                continue
            
            try:
                student_data = {
                    'id': sc.student.id,
                    'username': sc.student.username,
                    'student_id': sc.student.student_profile.student_id if sc.student.student_profile else None,
                    'first_name': sc.student.first_name or '',
                    'last_name': sc.student.last_name or '',
                    'email': sc.student.email or '',
                    'phone': sc.student.phone or '',
                    'score': float(sc.score) if sc.score else None,
                    'midterm_score': float(sc.midterm_score) if sc.midterm_score else None,
                    'final_score': float(sc.final_score) if sc.final_score else None,
                    'letter_grade': sc.letter_grade,
                    'status': sc.status,
                    'attendance_rate': float(sc.attendance_rate) if sc.attendance_rate else None
                }
                students.append(student_data)
            except Exception as e:
                print(f"Warning: Failed to process student record {sc.id}: {str(e)}")
                continue
        
        # 按成绩排序
        students.sort(key=lambda x: x['score'] if x['score'] else 0, reverse=True)
        
        return jsonify({
            'success': True,
            'data': {
                'course': course.to_dict(),
                'students': students,
                'total': len(students)
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/courses/statistics', methods=['GET'])
@jwt_required()
def get_course_statistics():
    """获取课程统计信息"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if current_user.role != 'admin':
            return jsonify({
                'success': False,
                'error': 'Permission denied'
            }), 403
        
        from app.models.student_course import StudentCourse
        
        total_courses = Course.query.count()
        
        # 按院系统计
        departments = db.session.query(
            Course.department,
            db.func.count(Course.id).label('count')
        ).group_by(Course.department).all()
        
        department_stats = {dept: count for dept, count in departments if dept}
        
        # 按学期统计
        semesters = db.session.query(
            Course.semester,
            db.func.count(Course.id).label('count')
        ).group_by(Course.semester).all()
        
        semester_stats = {sem: count for sem, count in semesters if sem}
        
        # 选课统计
        total_enrollments = StudentCourse.query.count()
        
        return jsonify({
            'success': True,
            'data': {
                'total_courses': total_courses,
                'total_enrollments': total_enrollments,
                'by_department': department_stats,
                'by_semester': semester_stats
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

